<template>
  <el-card>
    <div style="margin-bottom: 10px">
      <!-- 新增分区选择器 -->
      <el-cascader
        v-model="selectedZone"
        :options="zones"
        :props="{ expandTrigger: 'hover', emitPath: false, checkStrictly: true }"
        @change="handleZoneChange"
        placeholder="选择分区"
        style="width: 180px"
      >
      </el-cascader>

      <div style="float: right">
        <el-input v-model="inputTag" placeholder="请输入标签" style="width: 190px" />
        <el-button @click="showMonthlyData(inputTag)">分析</el-button>
      </div>
    </div>

    <el-tabs v-model="activeTab" v-loading="loading">
      <el-tab-pane label="词云图" name="cloud">
        <div ref="cloudChart" style="height: 600px; width: 100%"></div>
      </el-tab-pane>

      <el-tab-pane label="热度表格" name="table">
        排序依据：
        <el-select v-model="sortMetric" @change="onSortMetricChange" placeholder="排序依据" style="width: 180px">
          <el-option v-for="item in sortMetrics" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-table :data="pagedData" style="width: 100%">
          <el-table-column label="排名" min-width="60">
            <template #default="{ $index }">
              {{ $index + 1 + (currentPage - 1) * pageSize }}
            </template>
          </el-table-column>
          <el-table-column prop="tag" label="标签" min-width="120" />
          <el-table-column prop="count" label="出现次数" min-width="80" />
          <el-table-column prop="avgView" label="平均播放量" min-width="100" />
          <el-table-column prop="avgDanmaku" label="平均弹幕数" min-width="100" />
          <el-table-column prop="avgReply" label="平均评论数" min-width="100" />
          <el-table-column prop="avgLike" label="平均点赞数" min-width="100" />
          <el-table-column label="操作" min-width="80">
            <template #default="{ row }">
              <el-button size="small" @click="showMonthlyData(row.tag)">查看趋势</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="tableData.length"
          layout="prev, pager, next"
          style="margin-top: 16px; text-align: right"
        />
      </el-tab-pane>

      <!-- 新增月度数据标签页 -->
      <el-tab-pane label="月度趋势" name="monthly" v-if="selectedTag">
        <div>
          <h3 style="text-align: center; margin-bottom: 20px">{{ selectedTag }} 月度数据趋势</h3>
          <div ref="monthlyChart" style="height: 600px"></div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </el-card>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import * as echarts from 'echarts'
import 'echarts-wordcloud'
import { useApi } from '@/composables/useApi'
import partitionData from '@/assets/partition.json'

const http = useApi()

// 分区列表（与月度分析页面保持一致）
const zones = partitionData
const selectedZone = ref(0) // 默认选中全部分区

// 图表相关
const cloudChart = ref(null)
const monthlyChart = ref(null)
let myCloudChart = null
let myMonthlyChart = null

// 数据相关
const hotTags = ref([])
const tableData = ref([])
const sortedData = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const selectedTag = ref('')
const inputTag = ref('')
const tagMonthlyData = ref([])

// 加载提示
const loading = ref(false)

// 分页数据
const pagedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return sortedData.value.slice(start, start + pageSize.value)
})

// 标签页和排序相关
const activeTab = ref('cloud')
const sortMetrics = [
  { value: 'count', label: '出现次数' },
  { value: 'avgView', label: '平均播放量' },
  { value: 'avgLike', label: '平均点赞数' },
  { value: 'avgReply', label: '平均评论数' },
]
const sortMetric = ref('count')

// 指标配置（用于月度数据图表）
const metrics = [
  { key: 'view', name: '播放量' },
  { key: 'danmaku', name: '弹幕数' },
  { key: 'reply', name: '评论数' },
  { key: 'like', name: '点赞数' },
  { key: 'coin', name: '投币数' },
  { key: 'favorite', name: '收藏数' },
  { key: 'count', name: '视频数' },
]

// 加载热门标签数据
const loadHotTags = async () => {
  try {
    loading.value = true
    // 新增分区参数
    const res = await http.get('/tag/hotTag', {
      params: { tid: selectedZone.value },
    })
    loading.value = false

    if (res && res.code === 200) {
      // 表格数据：按选择的指标排序
      tableData.value = [...res.data]
      onSortMetricChange()

      // 词云数据：取前100个标签
      hotTags.value = tableData.value.slice(0, 100).map((item) => ({
        name: item.tag,
        value: item.count,
      }))
    }
  } catch (e) {
    console.error('获取热门标签失败', e)
  }
}

// 处理分区变化
const handleZoneChange = () => {
  currentPage.value = 1 // 重置分页
  loadHotTags() // 重新加载数据
}

// 处理排序变化
const onSortMetricChange = () => {
  sortedData.value = [...tableData.value].sort((a, b) => {
    return b[sortMetric.value] - a[sortMetric.value]
  })
}

// 查看标签月度数据
const showMonthlyData = async (tag) => {
  selectedTag.value = tag
  activeTab.value = 'monthly' // 切换到月度数据标签页

  loading.value = true
  try {
    const res = await http.get('/tag/getDataMonthly', {
      params: { tag },
    })

    if (res && res.code === 200) {
      tagMonthlyData.value = res.data
      renderMonthlyChart()
    }
  } catch (e) {
    console.error(`获取标签${tag}的月度数据失败`, e)
  }
  loading.value = false
}

// 渲染词云图
const renderCloudChart = () => {
  if (!cloudChart.value || !hotTags.value.length) return

  if (!myCloudChart) {
    myCloudChart = echarts.init(cloudChart.value)
    window.addEventListener('resize', () => {
      myCloudChart.resize()
      if (myMonthlyChart) myMonthlyChart.resize()
    })
  }

  const option = {
    series: [
      {
        type: 'wordCloud',
        shape: 'circle',
        gridSize: 6,
        sizeRange: [20, 100],
        rotationRange: [-90, 90],
        rotationStep: 45,
        left: 'center',
        top: 'center',
        width: '90%',
        height: '90%',
        maxCount: 100,
        textStyle: {
          color: () => {
            const colors = ['#ff69b4', '#fb7299', '#aeefff', '#00bfff', '#8ecae6', '#b4aee8', '#c1e1ff']
            return colors[Math.floor(Math.random() * colors.length)]
          },
          fontFamily: 'Impact, sans-serif',
        },
        emphasis: {
          textStyle: {
            shadowBlur: 10,
            shadowColor: '#333',
          },
        },
        data: hotTags.value,
      },
    ],
  }

  myCloudChart.setOption(option)
}

// 渲染月度数据图表
const renderMonthlyChart = () => {
  if (!monthlyChart.value || !tagMonthlyData.value.length) return

  if (!myMonthlyChart) {
    myMonthlyChart = echarts.init(monthlyChart.value)
  }

  const months = tagMonthlyData.value.map((item) => item.month)

  // 更精细的指标分组，每组单独Y轴
  const yAxisGroups = [
    { indices: [0], name: '播放量', color: '#337ab7' }, // 播放量
    { indices: [1], name: '弹幕数', color: '#5cb85c' }, // 单独弹幕
    { indices: [2], name: '评论数', color: '#f0ad4e' }, // 单独评论
    { indices: [3, 4, 5], name: '三连量', color: '#d9534f' }, // 点赞、投币、收藏
    { indices: [6], name: '视频数', color: '#5bc0de' }, // 单独视频数
  ]

  // 计算每组数据的最大值，用于优化坐标轴范围
  const groupMaxValues = yAxisGroups.map((group) => {
    return Math.max(
      ...group.indices.flatMap((idx) => {
        const metricKey = metrics[idx].key
        return tagMonthlyData.value.map((item) => item[metricKey])
      }),
    )
  })

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
      },
    },
    legend: {
      data: metrics.map((m) => m.name),
      // 固定图例位置在顶部左侧，避免随数据变化
      top: 10,
      left: 'center',
      width: '90%',
      // 强制图例水平排列并自动换行
      type: 'scroll',
      orient: 'horizontal',
      padding: [5, 0],
      itemGap: 15,
      // 固定每行显示4个图例，避免布局跳动
      pageButtonItemGap: 5,
      pageButtonGap: 10,
    },
    grid: {
      // 增加顶部距离避免图例与图表重叠
      top: '15%',
      left: '8%',
      right: '18%',
      bottom: '5%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      boundaryGap: true,
      data: months,
    },
    yAxis: yAxisGroups.map((group, index) => {
      // 动态计算坐标轴最大值，留10%余量使趋势更明显
      const maxVal = groupMaxValues[index]
      const axisMax = maxVal > 0 ? Math.ceil(maxVal * 1.1) : 100

      return {
        type: 'value',
        name: group.name,
        position: index === 0 ? 'left' : 'right',
        offset: index > 1 ? (index - 1) * 80 : 0, // 右侧轴偏移
        axisLine: { lineStyle: { color: group.color } },
        axisLabel: {
          formatter: (value) => {
            if (value >= 10000) return (value / 10000).toFixed(1) + '万'
            if (value >= 1000) return (value / 1000).toFixed(1) + 'k'
            return value
          },
        },
        max: axisMax, // 设置坐标轴最大值
        splitLine: { show: index === 0 }, // 只显示第一个Y轴的网格线
      }
    }),
    series: metrics.map((metric, metricIndex) => {
      const yAxisIndex = yAxisGroups.findIndex((group) => group.indices.includes(metricIndex))

      return {
        name: metric.name,
        type: metric.name === '视频数' ? 'bar' : 'line',
        data: tagMonthlyData.value.map((item) => item[metric.key]),
        smooth: true,
        yAxisIndex,
        lineStyle: { width: 2.5 },
        itemStyle: { radius: 4 },
        emphasis: {
          scale: true,
          itemStyle: { shadowBlur: 10 },
        },
      }
    }),
    animation: true,
    animationDuration: 1200,
  }

  myMonthlyChart.setOption(option)
}

// 监听热门标签变化，重新渲染词云
watch(
  hotTags,
  () => {
    renderCloudChart()
  },
  { immediate: true },
)

// 监听月度数据变化，重新渲染图表
watch(tagMonthlyData, () => {
  renderMonthlyChart()
})

// 页面挂载时加载数据
onMounted(() => {
  loadHotTags()
})
</script>
